package cn.buk.tms.eotms.dao;

import cn.buk.common.util.DateUtil;
import cn.buk.tms.eotms.entity.OrderNoInfo;
import org.springframework.stereotype.Repository;

import jakarta.transaction.Transactional;
import java.util.List;

/**
 * @author yfdai
 */
@Repository
@Transactional
public class OrderNoGeneratorImpl extends AbstractDao implements OrderNoGenerator {
  @Override
  public String generateOrderNo(int enterpriseId, String orderType) {
    String retVal = null;

    String hsql = "select o from OrderNoInfo o where o.enterpriseId = :enterpriseId and o.orderType = :orderType";

    List<OrderNoInfo> infos =
            em.createQuery(hsql, OrderNoInfo.class)
                    .setParameter("enterpriseId", enterpriseId)
                    .setParameter("orderType", orderType)
                    .getResultList();

    OrderNoInfo info = null;
    if (infos.size() == 1) {
      info = infos.get(0);
    }

    if (info == null) {
      info = new OrderNoInfo();
      info.setEnterpriseId(enterpriseId);
      info.setOrderType(orderType);
      info.setOrderNoValue(1);
      em.persist(info);
      em.flush();
    } else {
      int status = em.createQuery("update OrderNoInfo o set o.orderNoValue = o.orderNoValue + 1, o.lastUpdate = :lastUpdate " +
              "where o.id = :id")
              .setParameter("id", info.getId())
              .setParameter("lastUpdate", DateUtil.getCurDateTime())
              .executeUpdate();
      if (status != 1) {
        throw new RuntimeException("To get new order no failed.");
      }
      em.refresh(info);
    }

    retVal = orderType + info.getOrderNoValue();

    return retVal;
  }
}
